package net.expectx.common.single.util;

import net.expectx.common.single.base.BaseConstants;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 网络连接状态判断工具类
 * @author lijian
 */
public class NetStateUtil {
    static HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    public static Boolean connectingAddress(String remoteInetAddr){
        boolean flag=false;
        String tempUrl=remoteInetAddr.substring(0, 5);
        if(tempUrl.contains(BaseConstants.NETWORKING_PROTOCOL_HTTP)){
            if(BaseConstants.NETWORKING_PROTOCOL_HTTP.equals(tempUrl)){
                try {
                    trustAllHttpsCertificates();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
            }
            flag=isConnServerByHttp(remoteInetAddr);
        }else{
            flag=isReachable(remoteInetAddr);
        }
       return flag;
    }
    /**
     * 传入需要连接的IP，返回是否连接成功
     *
     * @param remoteInetAddr
     * @return
     */
    public static boolean isReachable(String remoteInetAddr) {
        boolean reachable = false;
        try {
            InetAddress address = InetAddress.getByName(remoteInetAddr);
            reachable = address.isReachable(1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reachable;
    }
    public static boolean isConnServerByHttp(String serverUrl) {
        boolean connFlag = false;
        URL url;
        HttpURLConnection conn = null;
        try {
            url = new URL(serverUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3 * 1000);
            if (conn.getResponseCode() == BaseConstants.STATUS_OK) {
                connFlag = true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }
        return connFlag;
    }
    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new MiTm();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());
    }
    static class MiTm implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return;
        }
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public boolean isServerTrusted(
                X509Certificate[] certs) {
            return true;
        }
        public boolean isClientTrusted(
                X509Certificate[] certs) {
            return true;
        }
        @Override
        public void checkClientTrusted(
                X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }
    public static void main(String [] args){
        NetStateUtil netStateUtil=new NetStateUtil();
        String url1="http://127.0.0.1:6001";
        System.out.println(url1+":"+ NetStateUtil.connectingAddress(url1));
       // System.out.println(url2+":"+netStateUtil.connectingAddress(url2));
       // System.out.println(url3+":"+netStateUtil.connectingAddress(url3));
    }
}
